package ro.bluecube.admlocal.delegates;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import ro.bluecube.admlocal.users.UsersServiceRemote;
import ro.bluecube.admlocal.users.entity.User;

/**
 * @author anton
 * 
 */
public class UserDelegate {

	private static final Logger log = Logger.getLogger(UserDelegate.class
			.getName());

	UsersServiceRemote service;
	
	private static UserDelegate instance;
	
	public static UserDelegate getInstance(){
		if (instance == null){
			instance = new UserDelegate();
		}
		return instance;
	}
	
	private UserDelegate() {
		super();
		final String jndiName = "UsersServiceImpl/remote";

		Context ic;
		try {

			ic = new InitialContext(System.getProperties());
			Object obj = ic.lookup(jndiName);
			service = (UsersServiceRemote) obj;
		} catch (NamingException e) {
			log.info(e.getMessage());
			log.info("naming exception");
			service = null;
		}
	}

	public boolean autentificare(String name, String password) {
		// String endpoint = "http://localhost:8080/webservice/soap/adminlocal";
		//
		// String addUserMethod = "addUser";
		// String authenticateUserMethod = "authenticateUser";
		// String in0 = "costas";
		// String in1 = "berlin";
		//
		// Service service = new Service();
		// Call call;
		// call = (Call) service.createCall();
		//
		// call.setTargetEndpointAddress(new java.net.URL(endpoint));
		// call.setOperationName(new QName("urn:soap.easoft.adminlocal.ro",
		// authenticateUserMethod));
		//
		// call.addParameter("in0", XMLType.XSD_STRING, ParameterMode.IN);
		// call.addParameter("in1", XMLType.XSD_STRING, ParameterMode.IN);
		//
		// call.setReturnType(org.apache.axis.encoding.XMLType.XSD_BOOLEAN);
		//
		// // call.invoke( new Object[] { in0, in1 } );
		// Boolean ret = (Boolean) call.invoke(new Object[] { in0, in1 });

		return true;
	}

	@SuppressWarnings("unchecked")
	public Collection<User> findAllUsers() {
		List usersList = null;
		if (service != null) {
			usersList = (List) service.getAllUsers();
		} else {
			usersList = new ArrayList<User>();
		}
		return usersList;
	}

	public void addUser(User user) {
		if (service != null) {
			service.addUser(user);
		} else {
			log.info("ERROR: service not found!!!");
		}
	}
}
